package com.run_java_test.test6;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

public class DynamicJarLoader {
    private URLClassLoader classLoader;

    public void loadJar(String jarPath) throws Exception {
        File jarFile = new File(jarPath);
        URL jarUrl = jarFile.toURI().toURL();
        this.classLoader = new URLClassLoader(new URL[]{jarUrl}, Thread.currentThread().getContextClassLoader());
    }

    public Class<?> loadClass(String className) throws ClassNotFoundException {
        if (this.classLoader == null) {
            throw new IllegalStateException("JAR is not loaded.");
        }
        return this.classLoader.loadClass(className);
    }

    public void close() throws IOException {
        if (this.classLoader != null) {
            this.classLoader.close();
        }
    }
}
